package com.pijunn.util

import com.pijunn.common.template.TemplateHolder
import groovy.text.SimpleTemplateEngine;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware
import org.springframework.mail.MailException
import org.springframework.mail.MailSender
import org.springframework.mail.javamail.MimeMessageHelper

import javax.mail.internet.MimeMessage
import javax.mail.internet.InternetAddress;


class EmailerService implements ApplicationContextAware {
	boolean transactional = false
	MailSender mailSender
	ApplicationContext applicationContext
	def groovyPagesTemplateEngine
	
//	MailPropertiesBean mailPropertiesBean
 
	def sendEmail(mail) throws MailException {
 
		MimeMessage mimeMessage = mailSender.createMimeMessage()
 
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "ISO-8859-1");
		helper.setFrom("support@pijunn.com");
		helper.setTo(getInternetAddresses(mail.to));
		helper.setSubject(mail.subject);
		helper.setText(mail.text, true);
		if(mail.bcc) helper.setBcc(getInternetAddresses(mail.bcc));
		if(mail.cc) helper.setCc(getInternetAddresses(mail.cc));
 
		mailSender.send(mimeMessage)
	}
	
	def sendNotificationEmail(TemplateHolder template){ 
		File tplFile = applicationContext.getResource( "/WEB-INF/mail-templates/Main.gsp")?.getFile(); 
		assert tplFile?.exists()
		def binding = ["${template.bindingName}": template.binding, "title": template.subject, "template": template.bindingName] 
		def output = new StringWriter()
		def tpl = groovyPagesTemplateEngine.createTemplate(tplFile).make(binding).writeTo(output)
		def body = output.toString()
		
		def email = [ 
			to: template.to, // "to" expects a List 
			subject: template.subject, 
			text: body 
		]
		
		try { 
			sendEmail(email) 
		} 
		catch (MailException ex) { 
			log.error("Failed to send emails", ex) 
			return false 
		} 
		
		return true 
	}
 
	private InternetAddress[] getInternetAddresses(List emails){
		InternetAddress[] mailAddresses = new InternetAddress[emails.size()];
		emails.eachWithIndex {mail, i ->
				mailAddresses[i] = new InternetAddress(mail)
		}
		return mailAddresses;
	}
 
}
